<?php

namespace app\api\controller\xiservice;

use addons\xiservice\controller\WeixinMini;
use app\common\controller\xiservice\XiserviceApi;
use app\common\model\xiservice\User as XiserviceUser;
use app\common\model\xiservice\ServiceTag;
use app\common\model\xiservice\Benfit;
use app\common\model\xiservice\Refuse;
use app\common\model\xiservice\Schedule as ScheduleModel;
use app\common\model\xiservice\Timelist;
use app\common\model\xiservice\Area;
use app\common\model\xiservice\ServiceCategory as ServiceCategoryModel;
use app\common\model\xiservice\ServiceTag as ServiceTagModel;
use app\common\model\xiservice\Message;
use app\common\model\xiservice\Messageread;
use fast\Random;
use think\Db;
use AlibabaCloud\SDK\Dyplsapi\V20170525\Dyplsapi;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dyplsapi\V20170525\Models\BindAxbRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

use AlibabaCloud\SDK\Dyplsapi\V20170525\Models\BindAxnRequest;
/**
 * 服务人员模块
 */
class Worker extends XiserviceApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $ordermodel = null;
    protected $refusemodel = null;
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->refusemodel = new \app\common\model\xiservice\Refuse();
        $this->ordermodel = new \app\common\model\xiservice\Order();
        $this->model = new \app\common\model\xiservice\User();
    }
    public function bindAxb()
    {
        $config = new Config([
            "accessKeyId" => "LTAI5tJ4dtHvxJXpDAJTRuFN",
            "accessKeySecret" => "9Aafg08e9GCVFGB9ZJhYMSvYBzRA0U"
        ]);
        $config->endpoint = "dyplsapi.aliyuncs.com";
        $client = new Dyplsapi($config);
        $bindAxnRequest = new BindAxnRequest([
            "poolKey" => "FC100000180222320",
            "phoneNoA" => "13568996287",
            "phoneNoB" => "15808142201",
            "expiration" => "2024-08-16 01:14:00"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response= $client->bindAxnWithOptions($bindAxnRequest, $runtime);
            $bindarray =json_decode(json_encode($response),true);
            if($bindarray && $bindarray['body'] && $bindarray['body']['secretBindDTO'])
            {
                $virtual_number = $bindarray['body']['secretBindDTO']['secretNo'];
                Db::name('user')->where(['id'=>16])->update(["virtual_number"=>$virtual_number]);
            }
            $string = json_encode($response);
        }
        catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }
    /**
     * @ApiTitle (申请)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.worker/apply)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','username':'string','avatar':'string','mobile':'int','addressnums':'int','collectnums':'int','ordernums':'int'}", description="返回数据")
     */

    public function apply()
    {
        $param = $this->request->post('', '', 'trim,strip_tags');
        

        $param['credit_score'] = 100;
        $check = XiserviceUser::where("user_id", $this->auth->id)
            ->where("checkinfo", 0)
            ->find();
        
        
        if ($check) {
            $this->error('正在审核中不能重复提交！');
        }
        $user = XiserviceUser::where('user_id', $this->auth->id)->find();

        // echo "<pre>";
        // print_r($user['bond_status']);die;

        $areaInfo = Area::where('level', 3)->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $param['lat'] . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $param['lat'] . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $param['lng'] . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance asc')
            ->find();
        if ($areaInfo) {
            $provinceInfo = Area::where('id', $areaInfo['pid'])->find();
            if ($provinceInfo) {
                $param['province_id'] = $provinceInfo['pid'];
                // $param['citytxt']= $provinceInfo['name'];
            }
            $param['city_id'] = $areaInfo['pid'];
            $param['area_id'] = $areaInfo['id'];
        }
        $param['checkinfo'] = 0;
        $param['work_start_time'] = '09:00:00';
        $param['work_end_time'] = '18:00:00';
        
        if($user['bond_status'] != 1){
            $param['bond_status'] = 2;
        }
        
        $order_no = 'DP' . date("YmdHis") . mt_rand(1000, 9999) . 16;
        $param['order_no'] = $order_no;
        $param['group_id'] = 1;
        $param['is_sq'] = 1;
        $param['auth_status'] = 0;
       

        $res = $this->model->allowField(true)->save($param, ['user_id' => $this->auth->id]);
        
        if($param['type'] == 1){
            $this->success('请等待审核', ['wxconfig' => [],]);
        }

        //   echo "<pre>";
        // print_r($user['bond_status']);die;

        if($user['bond_status'] != 1){
            $orderpay = array(
                'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                'out_trade_no' => $order_no,//订单号
                'body' => '保证金',//
                'total_fee' => $param['pay_money'],//支付金额，这边传单位为元的就可以。
                'openid' => $user['mini_openid'],//用户openID
            );
            $wx = new WeixinMini();
            $ret = $wx->union_order($orderpay);
            // echo "<pre>";
            // print_r($ret);die;
            if ($ret['status']) {
            $this->success('请等待审核', ['wxconfig' => $ret['wxconfig'],]);
            } else {
            $this->error("入驻失败", ['wxconfig' => [],]);
            }
        }else{
            $this->success('请等待审核', ['wxconfig' => [],]);
        }
    }


  
    /**
     * @ApiTitle (入库)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.worker/warehousing)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','username':'string','avatar':'string','mobile':'int','addressnums':'int','collectnums':'int','ordernums':'int'}", description="返回数据")
     */

     public function warehousing(){
      //  $param = $this->request->post('', '', 'trim,strip_tags');
        $param['user_id'] =  $this->auth->id;
        $param['train_id'] = input('param.train_id');
        $param['order_no'] = 'PX' . date("YmdHis") . mt_rand(1000, 9999);
        $param['money'] = input('param.money');
        $param['unid_name'] = input('param.unid_name');
        $param['address'] = input('param.address');
        $param['zhiwui'] = input('param.zhiwui');
        $param['exam_time'] = input('param.exam_time');
        $param['card_id_zm'] = input('param.idcard_front_image');
        $param['card_id_fm'] = input('param.idcard_back_image');
        $param['gw_front_image'] = input('param.gw_front_image');
        $param['jx_front_image'] = input('param.jx_front_image');
        $param['zhicheng'] = input('param.zhicheng');
        $param['status'] = 2;
        $param['order_time'] = time();
        $param['name'] = input('param.name');
        $param['sex'] = input('param.sex');
        $param['age'] = input('param.age');
        $param['phone'] = input('param.phone');
        $param['email'] = input('param.email');
        $param['region'] = input('param.region');

        $res = Db::name('train_order')->insert($param);
        if($res){
            $user = XiserviceUser::where('user_id', $this->auth->id)->find();
            $orderpay = array(
                'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
                'out_trade_no' => $param['order_no'],//订单号
                'body' => '培训费用',//
                'total_fee' => $param['money'],//支付金额，这边传单位为元的就可以。
                'openid' => $user['mini_openid'],//用户openID
            );
            $wx = new WeixinMini();
            $ret = $wx->union_order($orderpay);
            if ($ret['status']) {
                $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'],]);
            } else {
                $this->error("创建微信订单失败", ['wxconfig' => [],]);
            }
        }else{
            $this->error('下单失败');
        }
     }


    /**
     * @ApiTitle (修改个人信息)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiservice.worker/edit)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','username':'string','avatar':'string','mobile':'int','addressnums':'int','collectnums':'int','ordernums':'int'}", description="返回数据")
     */

    public function edit()
    {
        $param = $this->request->post('', '', 'trim,strip_tags');
        $check = XiserviceUser::where("user_id", $this->auth->id)
            ->where("checkinfo", 1)
            ->find();

        $areaInfo = Area::where('level', 3)->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $param['lat'] . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $param['lat'] . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $param['lng'] . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance asc')
            ->find();
        if ($areaInfo) {
            $provinceInfo = Area::where('id', $areaInfo['pid'])->find();
            if ($provinceInfo) {
                $param['province_id'] = $provinceInfo['pid'];
            }
            $param['city_id'] = $areaInfo['pid'];
            $param['area_id'] = $areaInfo['id'];
        }
        $res = $this->model->allowField(true)->save($param, ['user_id' => $this->auth->id]);
        $this->success('提交成功');
    }


    /**
     * @ApiTitle (服务人员信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/info)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','username':'string','avatar':'string','mobile':'int','addressnums':'int','collectnums':'int','ordernums':'int'}", description="返回数据")
     */
    public function info()
    {

        $user = XiserviceUser::where('user_id', $this->auth->id)->find();
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        if ($user) {
            //服务标签
            $user['tag'] = ServiceTag::where('id', 'in', $user['service_tag_ids'])->field('id,name')->select();
            //待接订单
            $user['waitOrder'] = $this->ordermodel->where('worker_id', $user['id'])->where('order_status', '10')->count();
            //待服务订单
            $user['waitService'] = $this->ordermodel->where('worker_id', $user['id'])->where('order_type',10)->where('order_status', '30')->count();
            //服务中订单
            $user['inService'] = $this->ordermodel->where('worker_id', $user['id'])->where('order_status', '40')->count();
            //今日服务
            $user['todayService'] = $this->ordermodel->where('worker_id',$user['id'])->where('order_type',10)->where('order_status', 'in', '20,30,40,50')->where('service_start_time', 'between', [$beginToday, $endToday])->count();
            $user['totalService'] = $this->ordermodel->where('worker_id',$user['id'])->where('order_type',10)->where('order_status', 'in', '20,30,40,50')->count();

            //今日新增
            $user['todayOrder'] = $this->ordermodel->where('worker_id', $user['id'])->where('order_type',10)->where('order_status', 'in', '20,30,40,50')->where('createtime', 'between', [$beginToday, $endToday])->count();
            //超时/拒绝
            $user['refuseOrder'] = $this->refusemodel->where('user_id', $user['id'])->count();

            $user['latestMsg'] = '暂无消息';
            $message = Message::with(['order' => function ($query) {
                $query->withField('order_no,confirm_time');
            }, 'service' => function ($query) {
                $query->withField('name,image');
            }, 'user' => function ($query) {
                $query->withField('username,mobile,avatar');
            }])
                ->where('type', 2)
                ->where('message.order_status', 1)
                ->where('to_user_id', $this->auth->id)
                ->order('createtime desc')
                ->find();
            if ($message) {
                $ret = Messageread::where('user_id', $this->auth->id)->where('message_id', $message['id'])->find();
                if (!$ret) {
                    $user['latestMsg'] = '您有新的订单消息';
                }
            }

            //未读系统消息
            $msgIds = Message::where('type', 1)->column('id');
            $rmsgIds = Messageread::where('user_id', $this->auth->id)->column('message_id');
            $array_diff = array_diff($msgIds, $rmsgIds);
            //未读订单消息
            $msgIds2 = Message::where('type', 2)->where('to_user_id', $this->auth->id)->column('id');
            $array_diff2 = array_diff($msgIds2, $rmsgIds);
            $alldiff = array_merge($array_diff, $array_diff2);

            $user['msgNum'] = count($alldiff);
            //今天收益
            $user['todayIncome'] = Benfit::where('type', 1)->where('user_id', $this->auth->id)->where('createtime', 'between', [$beginToday, $endToday])->sum('money');


            //技能证书
            $array = [];
            if ($user['extra_image']) {
                $user['extra_image_arr'] = explode(',', $user['extra_image']);
                if ($user['extra_image_arr']) {
                    for ($i = 0; $i < count($user['extra_image_arr']); $i++) {
                        $url = cdnurl($user['extra_image_arr'][$i], true);
                        array_push($array, $url);
                    }
                }
            } else {
                $user['extra_image_arr'] = [];
            }

            $user['extra_image_arr_url'] = $array;

        }

        $this->success('查询成功', $user);
    }

    /**
     * @ApiTitle (服务人员标签信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/servicetaglist)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{}", description="返回数据")
     */
    public function servicetaglist()
    {
        $list = ServiceTagModel::where('status', 1)
            ->order('weigh desc')
            ->field(['*,0 as active'])
            ->select();
        $user = XiserviceUser::where('user_id', $this->auth->id)->find();
        if ($list) {
            if ($user['service_tag_ids']) {
                $array = explode(',', $user['service_tag_ids']);
                for ($i = 0; $i < count($list); $i++) {
                    if ($array) {
                        if (in_array($list[$i]['id'], $array)) {
                            $list[$i]['active'] = 1;
                        } else {
                            $list[$i]['active'] = 0;
                        }
                    } else {
                        $list[$i]['active'] = 0;
                    }
                }
            } else {
                for ($i = 0; $i < count($list); $i++) {
                    $list[$i]['active'] = 0;
                }
            }
        }
        $this->success('查询成功', $list);
    }

    /**
     * @ApiTitle    (获取服务人员收益情况)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/benfit)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'id':'int','name':'string','image':'string','bargain':'int','saleprice':'float','basicnums':'int','salenums':'int'}", description="返回数据")
     */
    public function benfit()
    {
        $data = XiserviceUser::where('user_id', $this->auth->id)
            ->field('freeze_money,can_money,total_money')
            ->find();
        if ($data) {
            $data['today_money'] = Benfit::where('user_id', $this->auth->id)
                ->whereTime('createtime', 'today')
                ->sum('money');
        }
        $this->success('查询成功', $data);
    }



    public function quotelist()
    {
        $order_id = $this->request->request('order_id');
        $userinfos= Db::query('select f.*,f2.amount,FROM_UNIXTIME(f2.createtime) as quotetime,f2.order_id from fa_xiservice_user f inner join fa_xiservice_user_quote f2 on f.user_id=f2.user_id
        where  group_id=2 and work_status=1 and status=1 and checkinfo=1 and f2.order_id=:order_id;',['order_id'=>$order_id]);
        foreach($userinfos as $key=> $userinfo)
        {
            $categoryids = $userinfo['service_category_id'];
            $fruits = explode(",",$categoryids);
            $categorynames ='';
            foreach ($fruits as$fruit) {
                $cmodel = Db::name('xiservice_service_category')->where('id='.$fruit)->field('name')->find();
                $categorynames= $categorynames. $cmodel['name'].' ';
            }
            $userinfos[$key]['categoryname']=  $categorynames;
        }
       
        $this->success('查询成功', $userinfos);

    }
    public function gettraindetail()
    {
        $id = $this->request->request('id');
        $trainList = Db::name('train_time')->where(['train_id'=>$id])->select();
        $trainArry=[];
        foreach( $trainList as $item)
        {
            $trainArry[]=$item['timetrain'];
        }
        $this->success('查询成功', $trainArry);

    }
    /**
     * @ApiTitle    (获取服务人员列表)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/list)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="service_category_id", type="integer", description="服务分类id")
     * @ApiParams   (name="lat", type="float", description="纬度")
     * @ApiParams   (name="lng", type="float", description="经度")
     * @ApiParams   (name="reserve_time", type="integer", description="预约时间戳")
     * @ApiParams   (name="duration_time", type="integer", description="持续时间")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function list()
    {
        //获取附近的服务人员信息
        $serviceCategoryId = $this->request->request('service_category_id', 0);
        $lat = $this->request->request('lat');
        $lng = $this->request->request('lng');
        $reserve_time = $this->request->request('reserve_time');
        $duration_time = $this->request->request('duration_time');
        if (!$lat || !$lng) {
            $this->success('查询成功', []);
        }
        //根据经纬度检索服务人员
        //派单距离
        $distance = isset(config('xiservice.order')['auto_distance']) ? config('xiservice.order')['auto_distance'] * 1000 : 5000;
        $list = XiserviceUser::where('group_id', 2)
            ->where('FIND_IN_SET(:id,service_category_id)', ['id' => intval($serviceCategoryId)])
            ->where('work_status', 1)
            ->where('status', 1)
            ->where('checkinfo', 1)
            ->field("id,user_id,username,avatar,mobile,basic_service_num,work_start_time,work_end_time,service_num,review,level,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
        //    ->having("distance < {$distance}")
            ->order('distance asc')
            ->select();
        if (!$list) {
            $this->success('查询成功', []);
        }
        $count = $duration_time / 30;
        //时间分段
        $time_arr = [];
        array_push($time_arr, $reserve_time);
        if ($count > 1) {
            for ($i = 0; $i < $count; $i++) {
                $time = $reserve_time + 30 * 60 * ($i + 1);
                array_push($time_arr, $time);
            }
        } else {
            array_push($time_arr, $reserve_time + 30 * 60);
        }
        //判断服务人员时间上是否冲突
        $member = [];
        $work_end_time = $reserve_time + $duration_time * 60;
        for ($i = 0; $i < count($list); $i++) {
            //判断是否在当天工作时间之内
            $start_time = strtotime(date('Y-m-d', $reserve_time) . " " . $list[$i]['work_start_time']);
            $end_time = strtotime(date('Y-m-d', $reserve_time) . " " . $list[$i]['work_end_time']);

            if ($start_time <= $reserve_time && $work_end_time <= $end_time) {
                $check = ScheduleModel::where('user_id', $list[$i]['user_id'])->where('rest_timestamp', 'in', $time_arr)->find();
                if (!$check) {
                    array_push($member, $list[$i]);
                }
            }
        }
        $this->success('查询成功', $member);
    }

    /**
     * @ApiTitle    (获取最近7天)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/datelist)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function datelist()
    {
        $array = [];
        $weekarray = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        for ($i = 0; $i < 6; $i++) {
            $date01 = date('Y-m-d', time() + 86400 * $i);
            $date02 = date('m-d', time() + 86400 * $i);
            $date = ['date' => $date01, 'mdate' => $date02, 'week' => $weekarray[date("w", strtotime($date01))]];
            array_push($array, $date);
        }
        $this->success('查询成功', $array);
    }

    //保证金
    public function getdepositmoney()
    {
        $bonds = Db::name('bond')->value('bond_price');
        $this->success('查询成功', $bonds);
    }

    /**
     * @ApiTitle    (获取服务人员时间列表)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/schedule)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="date", type="date", description="日期")
     * @ApiParams   (name="worker_id", type="integer", description="服务人员id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function schedule()
    {


        $date = $this->request->request('date');
        $worker = XiserviceUser::where('user_id', $this->auth->id)->find();
        if (!$worker) {
            $this->error('服务人员不存在!');
        }
        if (!$worker['work_start_time']) {
            $this->error('暂未设置工作时间!');
        }
        $list = ScheduleModel::where('user_id', $worker['user_id'])
            ->where('date', $date)
            ->select();
        $Timelist = Timelist::where('start_time', '>=', $worker['work_start_time'])->where('end_time', '<=', $worker['work_end_time'])->order('id asc')->select();

        foreach ($Timelist as $row) {
            $row['checked'] = 1; //可选择
            $row['date'] = $date;
            $row['timestamp'] = strtotime($date . " " . $row['start_time']);
            $time = time();
            if ($row['timestamp'] < $time) {
                $row['checked'] = 0;
            }
            foreach ($list as $rows) {
                if ($row['start_time'] == $rows['rest_start_time']) {
                    $row['checked'] = 0;
                }
            }
            //订单工作时间过滤
        }
        $this->success('查询成功', $Timelist);
    }

    /**
     * @ApiTitle    (获取服务人员时间列表)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/timelist)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="date", type="date", description="日期")
     * @ApiParams   (name="worker_id", type="integer", description="服务人员id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function timelist()
    {
        $date = $this->request->request('date');
        $workerId = $this->request->request('worker_id');
        $list = ScheduleModel::where('user_id', $workerId)
            ->where('date', $date)
            ->select();
        $worker = XiserviceUser::where('id', $workerId)->find();
        if (!$worker) {
            $this->error('服务人员不存在!');
        }
        if (!$worker['work_start_time']) {
            $this->error('暂未设置工作时间!');
        }

        $Timelist = Timelist::where('start_time', '>=', $worker['work_start_time'])->where('end_time', '<=', $worker['work_end_time'])->order('id asc')->select();

        foreach ($Timelist as $row) {
            $row['checked'] = 1; //可选择
            $row['date'] = $date;
            $row['timestamp'] = strtotime($date . " " . $row['start_time']);
            $time = time();
            if ($row['timestamp'] < $time) {
                $row['checked'] = 0;
            }
            foreach ($list as $rows) {
                if ($row['start_time'] == $rows['rest_start_time']) {
                    $row['checked'] = 0;
                }
            }
            //订单工作时间过滤
        }
        $this->success('查询成功', $Timelist);
    }

    /**
     * @ApiTitle    (获取通用时间列表)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/common_timelist)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="date", type="date", description="日期")
     * @ApiParams   (name="service_time_unit", type="int", description="时间区分")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function common_timelist()
    {
        $date = $this->request->request('date');
        $service_time_unit = $this->request->request('service_time_unit');

        $Timelist = Timelist::order('id asc')->select();
        // $Timelist = Timelist::where('start_time', '>=', '09:00:00')->where('end_time', '<=', '19:00:00')->field(['*,0 as active'])->order('id asc')->select();
        $timearr = [];
        if ($service_time_unit == 30) {
            if ($Timelist) {
                foreach ($Timelist as $row) {
                    $row['checked'] = 1; //可选择
                    $row['date'] = $date;
                    $row['timestamp'] = strtotime($date . " " . $row['start_time']);
                    $time = time();
                    if ($row['timestamp'] > $time) {
                        array_push($timearr, $row);
                    }
                }
            }
        } else {
            if ($Timelist) {
                foreach ($Timelist as $row) {
                    $row['checked'] = 1; //可选择
                    $row['date'] = $date;
                    $row['timestamp'] = strtotime($date . " " . $row['start_time']);
                    $time = time() + 3 * 60 * 60;
                    if ($row['timestamp'] > $time) {
                        if (!strstr($row['start_time'], '30')) {
                            array_push($timearr, $row);
                        }
                    }
                }
            }
        }

        $this->success('查询成功', $timearr);
    }

    /**
     * @ApiTitle    (设置服务人员工作时间)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/chosetime)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="date", type="date", description="日期")
     * @ApiParams   (name="time", type="integer", description="time")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function chosetime()
    {
        $date = $this->request->request('date');
        $time = $this->request->request('time');

        $nowtime = time();
        $timestamp = strtotime($date . ' ' . $time);
        if ($timestamp < $nowtime) {
            $this->error('当前时间不可选', []);
        }
        $data = ScheduleModel::where('user_id', $this->auth->id)
            ->where('date', $date)
            ->where('rest_start_time', $time)
            ->find();
        if ($data) {
            if ($data['type'] == 2) {
                $this->error('当前时间已被预约不能修改', []);
            }
            $res = ScheduleModel::where('id', $data['id'])
                ->delete();
            $this->success('修改成功', []);
        } else {
            $vdata['user_id'] = $this->auth->id;
            $vdata['date'] = $date;
            $vdata['rest_start_time'] = $time;
            $vdata['rest_timestamp'] = $timestamp;
            $res = ScheduleModel::insertGetId($vdata);
            $this->success('修改成功', []);
        }
    }

    /**
     * @ApiTitle    (确认接单接口)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/sureorder)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="id", type="id", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function sureorder()
    {
        $id = $this->request->request('id');
        $order = $this->ordermodel->where('id', $id)
            ->where('worker_id', $this->auth->id)
            ->where('order_status', '20')
            ->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        $res = $this->ordermodel->changeOrderStatus($id, 'confirm');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $this->success('接单成功', []);
    }


    /**
     * @ApiTitle    (拒绝接单接口)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/xiservice.worker/refuseorder)
     * @ApiHeaders  (name=token, type=string, description="Token")
     * @ApiParams   (name="id", type="id", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="返回数据")
     */
    public function refuseorder()
    {
        $id = $this->request->request('id/d');
        $type = $this->request->request('type/d');

        $order = $this->ordermodel->where('id', $id)
            ->where('chose_type', 0)
            ->where('worker_id', $this->auth->id)
            ->where('order_status', '20')
            ->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }

        $res = $this->ordermodel->changeOrderStatus($id, 'refuse');
        if (!$res['status']) {
            $this->error($res['msg']);
        }

        $data['user_id'] = $this->auth->id;
        $data['order_id'] = $id;
        $data['createtime'] = time();
        $res = Refuse::insertGetId($data);
        if ($res) {
            $this->success('操作成功', []);
        } else {
            $this->error('网络错误请重试!', []);
        }
    }


    /**
     * @ApiTitle (取消订单信息)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/cancelorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function cancelorder()
    {
        $id = $this->request->request('id');
        $order = $this->ordermodel->where('worker_id', $this->auth->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        $time = time();
        $c = $order['service_start_time'] - $time;
        if ($order['order_status'] > 10) {
            if ($c < 10800) {
                $this->error('需要在预约时间提前3小时才能取消!', []);
            }
        }
        $res = $this->ordermodel->changeOrderStatus($id, 'cancel');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        //判断是否执行退款
        $this->success('取消成功', []);
    }

    /**
     * @ApiTitle (抢单)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/graborder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function graborder()
    {
        $id = $this->request->request('id');
        $order = $this->ordermodel->where('worker_id', 0)->where('order_status', 20)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
      //  $data['worker_id'] = $this->auth->id;

        $duration_time = $order['service_duration'];
        $reserve_time = $order['service_start_time'];
        $count = $duration_time / 30;
        //时间分段
        $time_arr = [];
        array_push($time_arr, $reserve_time);
        if ($count > 1) {
            for ($i = 0; $i < $count; $i++) {
                $time = $reserve_time + 30 * 60 * ($i + 1);
                array_push($time_arr, $time);
            }
        } else {
            array_push($time_arr, $reserve_time + 30 * 60);
        }
        //判断时间是否合适
        $worker = XiserviceUser::where('user_id', $this->auth->id)->find();

        $start_time = strtotime(date('Y-m-d', $reserve_time) . " " . $worker['work_start_time']);
        $end_time = strtotime(date('Y-m-d', $reserve_time) . " " . $worker['work_end_time']);

        $work_end_time = $reserve_time + $duration_time * 60;
        if ($start_time <= $reserve_time && $work_end_time <= $end_time) {
            $check = ScheduleModel::where('user_id', $worker['user_id'])->where('rest_timestamp', 'in', $time_arr)->find();
            // if ($check) {
            //     $this->error('当前时间已被预约不能抢单', []);
            // }
        } else {
            $this->error('非工作时间不能抢单', []);
        }

       // $req = $this->ordermodel->where('id', $id)->update($data);
        //$res = $this->ordermodel->changeOrderStatus($id, 'confirm');
        // if (!$res['status']) {
        //     $data['worker_id'] = 0;
        //     $req = $this->ordermodel->where('id', $id)->update($data);
        //     $this->error($res['msg']);
        // }
        //技术时间表更新
        $this->success('抢单成功', []);
    }

    /**
     * @ApiTitle (开始服务订单)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/startorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function startorder()
    {
        $id = $this->request->request('id');
        $userid = $this->request->request('userid');

        $order = $this->ordermodel->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', [],-1);
        }
        // $res = $this->ordermodel->changeOrderStatus($id, 'service');
        $current_time = time();
        $pay_time_plus_600= $order['pay_time']+600;
        if ($pay_time_plus_600 >$current_time) {
            $this->error('10分钟后才能开始服务');
        } 
        $this->success('操作成功', [],1);
    }

    public function update_user_apply_city()
    {
        $city = $this->request->request('city');
        $is_city_sq = 1;
        $userId = $this->auth->id;
        Db::execute('update fa_xiservice_user set sq_type=1,sq_citytet=:city,is_city_sq=:is_city_sq where user_id=:userid;',['city'=>$city,'is_city_sq'=>$is_city_sq,'userid'=>$userId]);
        $this->success('操作成功', [],1);
    }


    

    
    public function update_user_apply_image()
    {
        $service_category_id = $this->request->request('service_category_id');
        $images = $this->request->request('images');
        $is_add_sq = 1;
        $is_anniu_ht = 1;
 
        $userId = $this->auth->id;    
        Db::execute('update fa_xiservice_user set is_add_service_category_id=:service_category_id,add_images=:images,is_add_sq=:is_add_sq,is_anniu_ht=:is_anniu_ht where user_id=:userid;',['service_category_id'=>$service_category_id,'images'=>$images,'is_anniu_ht'=>$is_anniu_ht,
        'is_add_sq'=>$is_add_sq,'userid'=>$userId]);
        $this->success('申请成功', [],1);
    }
    public function update_user_apply_bank()
    {
    //     sq_price:that.data.pay_money,
	// bank:that.data.bank,
	// bank_addr:that.data.bank_addr,
	// tk_ret:that.data.tk_ret
        $sq_price = $this->request->request('sq_price');
        $bank = $this->request->request('bank');
        $bank_addr = $this->request->request('bank_addr');
        $tk_ret = $this->request->request('tk_ret');
        $is_bzje_sq = 1;
        $userId = $this->auth->id;
        Db::execute('update fa_xiservice_user set tk_type=1,sq_price=:sq_price,tk_ret=:tk_ret,bank=:bank,bank_addr=:bank_addr,is_bzje_sq=:is_bzje_sq where user_id=:userid;',['sq_price'=>$sq_price,'userid'=>$userId,'bank'=>$bank,'bank_addr'=>$bank_addr,'is_bzje_sq'=>$is_bzje_sq,'tk_ret'=>$tk_ret]);
        $this->success('操作成功', [],1);
    }

    /**
     * @ApiTitle (录入金额接口)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/inputorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function inputorder()
    {
        $id = $this->request->request('id');

       $orderxiservice = Db::name('xiservice_order')->where('id',$id)->find();
        $serviceidres = Db::name('xiservice_service')->where('id',$orderxiservice['service_id'])->find();
        //算总价
        $lowprice = $serviceidres['lowprice'] * $orderxiservice['area'];
       
        

        $cost = $this->request->request('cost');
         
             
        $order = $this->ordermodel->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }

        $userId = $this->auth->id;
        
        $usercredit_score = Db::name('xiservice_user')->where('user_id',$userId)->find();

       
        


        $serviceid=$order['service_id'];
        $serviceModel = Db::name('xiservice_service')->where('id', $serviceid)->find();
        // $lowprice = $serviceModel['lowprice'];
        $lowmsg='';

        if($usercredit_score['credit_score'] <= 60){
            $lowmsg='您的信誉分过低,请联系客服学习后从新接单';
            $this->success($lowmsg);  
            return;
        }
        if($lowprice)
        {
            if($lowprice>$cost)
            {
                $lowmsg='你的报价低于市场实际成本价格，可能会影响施工质量，请您重新报价，感谢您的参与!';
                $this->success($lowmsg);  
                return;
            }
        }
        
        

        $data['order_id'] = $order['id'];
        $data['amount'] = $cost;
        $data['user_id'] = $userId;
        $data['createtime'] = time();
        $map = Db::name('xiservice_user_quote')->where('user_id',$userId)->where('order_id',$order['id'])->find();

        // echo "<pre>";
        // print_r($map);die;
        if($map){
            $res = Db::name('xiservice_user_quote')->where('user_id',$userId)->where('order_id',$order['id'])->update($data);
        }else{
            $res = Db::name('xiservice_user_quote')->insert($data);
        }
        // $data['total_money'] = bcadd($cost, $order['visit_money'], 2);
        // $data['pay_money'] = bcadd($cost, $order['visit_money'], 2);
        // $data['bargain_status'] = 20;
        // $res = Db::name('xiservice_user_quote')->insert($data);
        // if($res){

            $order['quote_amount']=$cost;
              //推送订阅消息
              $msg = new \app\common\model\xiservice\Message();
              $msg->sendOrderMessage($order, 4);

            $this->success($lowmsg);  
        // }


       // $res = $this->ordermodel->where('id', $order['id'])->update($data);
        
    }

    /**
     * @ApiTitle (申请验证完工接口)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.worker/checkorder)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiParams  (name="iamges", type="sting", description="完工图片")
     * @ApiParams  (name="id", type="integer", description="订单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object",  description="返回数据")
     */
    public function checkorder()
    {
        $userInfo= Db::name('xiservice_user')->where(['user_id'=>$this->auth->id])->find();

        $id = $this->request->request('id');
        $images = $this->request->request('images');
        $remark = $this->request->request('remark');
        $order = $this->ordermodel->where('worker_id',  $userInfo['id'])->where('order_status', '40')->where('id', $id)->find();
        if (!$order) {
            $this->error('订单信息错误', []);
        }
        $data['service_check_images'] = $images;
        $data['construction_images'] = $images;
        $data['service_check_remark'] = $remark;
        $data['order_status']=70;
        $res = $this->ordermodel->where('id', $order['id'])->update($data);
           //推送订阅消息
           $msg = new \app\common\model\xiservice\Message();
           $msg->sendOrderMessage($order, 6);
        $this->success('申请成功', $res);
    }

   
}